# Author: jumpingzp
# Email: jumpingzp@gmail.com

from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from meet001.commentboard.models import CommentBoard
from meet001.commentboard.forms import AddCommentForm
from django.contrib.auth.models import User

COMMENT_BOARD_NOT_EXIST = 'COMMENT_BOARD_NOT_EXIST'
USER_NOT_EXIST = 'USER_NOT_EXIST'
UNKNOWN_ERROR = 'UNKNOWN_ERROR'

def set_nocache(response):
  response['cache-control'] = 'no-cache'
  return response

# handle /commentboard/display/
# return the retrieved comment board contents as xml
# if no board in database matches the id or no id field in request, return empty xml file
def display(request):
  if request.method != "GET":
    return set_nocache(render_to_response('commentboard_display.html', {}))
  if 'id' not in request.GET:
    return set_nocache(render_to_response('commentboard_display.html', {}))
  id = request.GET['id']
  board = CommentBoard.get_board(id)
  return set_nocache(render_to_response('commentboard_display.html', {'board':board}))

# handle /commentboard/addcomment/
# one should always use HTTP POST method to invoke the add operation
def add_comment(request):
  if request.method == "POST":
    return _add_post(request)
  else:
    return _add_get(request)  # for test purpose

def _add_post(request):
  errors=[]
  form = AddCommentForm(request.POST)
  if not form.is_valid():
    for key in form.errors.keys():
      errmsg = key + ': '
      errors.append(errmsg)
      for value in form.errors[key]:
        errmsg = value
        errors.append(errmsg)
    return render_to_response('commentboard_opresult.html', {'errors':errors})
  try:
    form.save(request.user)
  except User.DoesNotExist:
    # only for the design that user info is got by input user id when saving comments
    # if user info is got from request when saving comments, this exception will never be raised
    errors.append(USER_NOT_EXIST)
    return render_to_response('commentboard_opresult.html', {'errors':errors})
  except CommentBoard.DoesNotExist:
    errors.append(COMMENT_BOARD_NOT_EXIST)
    return render_to_response('commentboard_opresult.html', {'errors':errors})
  except:
    errors.append(UNKNOWN_ERROR)
    return render_to_response('commentboard_opresult.html', {'errors':errors})
  else:
    return render_to_response('commentboard_opresult.html', {})
  
# display a form to add comment, for test purpose
def _add_get(request):
  return render_to_response('commentboard_addcomment.html', {})
